<template>
  <div class="chat-mobile-view">
    <div class="mobile-header">
      <template v-if="showDetail && selectedUser">
        <div class="header-left">
          <el-button type="text" icon="el-icon-arrow-left" @click="backToList">返回</el-button>
          <div class="user-info">
            <el-avatar :size="32" icon="el-icon-user-solid"></el-avatar>
            <div class="info-text">
              <div class="user-name">用户 {{ selectedUser.client_uuid.substring(0, 8) }}</div>
              <div class="user-status">
                <span :class="['status-dot', selectedUser.is_online ? 'online' : 'offline']"></span>
                <span>{{ selectedUser.is_online ? '在线' : '离线' }}</span>
              </div>
            </div>
          </div>
        </div>
        <el-button type="text" class="header-refresh" @click="refreshCurrentUser">刷新</el-button>
      </template>
      <template v-else>
        <div class="header-title">聊天用户</div>
        <el-button type="text" class="header-refresh" @click="refreshUsers">刷新</el-button>
      </template>
    </div>

    <div class="content-area">
      <transition name="fade-slide" mode="out-in">
        <div v-if="!showDetail" key="list" class="user-list">
          <div
            v-for="user in onlineUsers"
            :key="user.client_uuid"
            class="user-card"
            @click="openChat(user)"
          >
            <div class="card-content">
              <div class="card-left">
                <div class="avatar-wrapper">
                  <el-avatar :size="44" icon="el-icon-user-solid"></el-avatar>
                  <span v-if="user.unread_count > 0" class="unread-badge">{{ user.unread_count > 99 ? '99+' : user.unread_count }}</span>
                </div>
                <div class="card-info">
                  <div class="card-name">用户 {{ user.client_uuid.substring(0, 8) }}</div>
                  <div class="card-status">
                    <span :class="['status-dot', user.is_online ? 'online' : 'offline']"></span>
                    <span>{{ user.is_online ? '在线' : '离线' }}</span>
                    <span class="last-time">{{ formatTime(user.last_active_time) }}</span>
                  </div>
                  <div class="card-message">
                    {{ user.last_message ? trimMessage(user.last_message) : '暂无消息' }}
                  </div>
                </div>
              </div>
              <el-button 
                type="text" 
                size="small" 
                class="delete-button" 
                icon="el-icon-delete" 
                @click.stop="confirmDeleteChat(user.client_uuid)" 
                title="删除聊天记录"
              >删除</el-button>
            </div>
          </div>
          <div v-if="onlineUsers.length === 0" class="empty-state">
            <el-empty description="暂无聊天用户"></el-empty>
          </div>
        </div>

        <div v-else key="detail" class="chat-detail">
          <div class="messages-container" ref="messagesContainer">
            <div
              v-for="message in messages"
              :key="message.id"
              :class="['message-row', message.sender_type === 2 ? 'service' : 'customer']"
            >
              <div class="message-bubble">
                <div v-if="message.message_type === 2 && message.image_url" class="message-image-wrapper">
                  <img
                    :src="getImageUrl(message.image_url)"
                    class="message-image"
                    @click="previewImage(getImageUrl(message.image_url))"
                    alt="图片"
                  />
                  <div
                    v-if="message.message && message.message !== '[图片]'"
                    class="message-caption"
                  >
                    <template v-if="message.message.includes('\n')">
                      <div class="caption-title">{{ message.message.split('\n')[0] }}</div>
                      <div class="caption-price">{{ message.message.split('\n')[1] }}</div>
                    </template>
                    <template v-else>
                      {{ message.message }}
                    </template>
                  </div>
                </div>
                <div v-else class="message-text">{{ message.message }}</div>
                <div class="message-time">{{ formatMessageTime(message.create_time) }}</div>
              </div>
            </div>
            <div v-if="messages.length === 0" class="empty-messages">
              <p>暂无消息，开始对话吧~</p>
            </div>
          </div>

          <div class="input-area">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="2"
              placeholder="输入消息..."
              @keydown.native="handleKeyDown"
            ></el-input>
            <div class="input-actions">
              <input
                type="file"
                ref="imageInput"
                accept="image/*"
                style="display: none"
                @change="handleImageSelect"
              />
              <el-button
                type="text"
                icon="el-icon-picture"
                @click="triggerImageUpload"
                :disabled="uploading"
              ></el-button>
              <el-button type="primary" @click="sendTextMessage" :loading="sending" :disabled="uploading">发送</el-button>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import {
  getOnlineUsers,
  getChatMessages,
  sendChatMessage,
  markChatAsRead,
  uploadChatImage
} from '@/api/contract';
import request from '@/utils/request';

export default {
  name: 'ChatManagementMobileView',
  data() {
    return {
      onlineUsers: [],
      selectedUser: null,
      messages: [],
      inputMessage: '',
      sending: false,
      uploading: false,
      showDetail: false,
      currentPage: 1,
      pageSize: 20,
      pollTimer: null
    };
  },
  methods: {
    async fetchOnlineUsers() {
      try {
        const response = await getOnlineUsers({
          page: 1,
          pageSize: 100
        });
        if (response.data.code === 200) {
          this.onlineUsers = response.data.data.list || [];
          if (this.selectedUser) {
            const updated = this.onlineUsers.find(u => u.client_uuid === this.selectedUser.client_uuid);
            if (updated) {
              this.selectedUser = { ...this.selectedUser, ...updated };
            }
          }
        } else {
          this.$message.error(response.data.msg || '获取用户失败');
        }
      } catch (error) {
        console.error('获取用户失败:', error);
      }
    },
    async openChat(user) {
      this.selectedUser = user;
      this.showDetail = true;
      await this.loadMessages();
      await this.markAsRead();
      this.$nextTick(() => this.scrollToBottom());
    },
    backToList() {
      this.showDetail = false;
      this.selectedUser = null;
      this.messages = [];
      this.inputMessage = '';
    },
    async refreshCurrentUser() {
      if (this.selectedUser) {
        await this.loadMessages();
        await this.fetchOnlineUsers();
      }
    },
    async loadMessages() {
      if (!this.selectedUser) return;
      const allMessages = [];
      let page = 1;
      const limit = this.pageSize;
      const maxLoops = 50;
      try {
        while (page <= maxLoops) {
          const response = await getChatMessages({
            client_uuid: this.selectedUser.client_uuid,
            page,
            pageSize: limit
          });
          if (response.data.code !== 200) {
            this.$message.error(response.data.msg || '加载消息失败');
            break;
          }
          const data = response.data.data || {};
          const list = data.list || [];
          allMessages.push(...list);
          const hasMore = this.hasMorePages(data, list.length, page, limit);
          if (!hasMore) {
            break;
          }
          page += 1;
        }
        this.messages = allMessages
          .slice()
          .sort((a, b) => Number(a.create_time) - Number(b.create_time));
        this.$nextTick(() => this.scrollToBottom());
      } catch (error) {
        console.error('加载消息失败:', error);
      }
    },
    hasMorePages(data, listLength, currentPage, limit) {
      if (!data) return false;
      const pagination = data.pagination || {};
      const totalPages =
        pagination.total_pages ||
        pagination.total_page ||
        pagination.last_page ||
        pagination.pages ||
        null;
      if (totalPages) {
        return currentPage < totalPages;
      }
      const total = data.total || data.total_count || data.count || null;
      if (total && total <= currentPage * limit) {
        return false;
      }
      return listLength >= limit;
    },
    async sendTextMessage() {
      if (!this.selectedUser) {
        this.$message.warning('请先选择用户');
        return;
      }
      const content = (this.inputMessage || '').trim();
      if (!content) {
        this.$message.warning('消息不能为空');
        return;
      }
      if (this.sending) return;
      this.sending = true;
      try {
        await sendChatMessage({
          client_uuid: this.selectedUser.client_uuid,
          sender_type: 2,
          message_type: 1,
          message: content
        });
        await this.loadMessages();
        await this.fetchOnlineUsers();
      } catch (error) {
        // console.error('发送失败:', error);
        // this.$message.error(error.message || '发送失败');
      } finally {
        this.inputMessage = '';
        this.sending = false;
      }
    }, 
    triggerImageUpload() {
      if (!this.selectedUser) {
        this.$message.warning('请选择用户');
        return;
      }
      this.$refs.imageInput.click();
    },
    async handleImageSelect(event) {
      const file = event.target.files[0];
      if (!file) return;
      if (!file.type.match('image.*')) {
        this.$message.error('请选择图片文件');
        event.target.value = '';
        return;
      }
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('图片大小不能超过5MB');
        event.target.value = '';
        return;
      }
      this.uploading = true;
      try {
        const response = await uploadChatImage(file);
        const data = response.data || {};
        const imageUrl =
          (data.data && data.data.image_url) ||
          data.image_url ||
          data.url ||
          data.path;
        if (imageUrl) {
          await this.sendImageMessage(imageUrl);
        } else {
          this.$message.error(data.msg || data.message || '图片上传失败');
        }
      } catch (error) {
        console.error('图片上传失败:', error);
        this.$message.error(error.message || '图片上传失败');
      } finally {
        this.uploading = false;
        event.target.value = '';
      }
    },
    async sendImageMessage(imageUrl) {
      if (!this.selectedUser || !imageUrl) return;
      if (this.sending) return;
      this.sending = true;
      try {
        await sendChatMessage({
          client_uuid: this.selectedUser.client_uuid,
          sender_type: 2,
          message_type: 2,
          image_url: imageUrl,
          message: '[图片]'
        });
        await this.loadMessages();
        await this.fetchOnlineUsers();
      } catch (error) {
        // console.error('发送失败:', error);
        // this.$message.error(error.message || '发送失败');
      } finally {
        this.sending = false;
      }
    },
    async markAsRead() {
      if (!this.selectedUser) return;
      try {
        await markChatAsRead({
          client_uuid: this.selectedUser.client_uuid,
          sender_type: 2
        });
      } catch (error) {
        console.error('标记已读失败:', error);
      }
    },
    scrollToBottom() {
      const container = this.$refs.messagesContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },
    formatTime(timestamp) {
      if (!timestamp) return '';
      const ts = Number(timestamp);
      if (isNaN(ts) || !isFinite(ts) || ts <= 0) return '';
      const date = new Date(ts.toString().length === 10 ? ts * 1000 : ts);
      if (isNaN(date.getTime())) return '';
      const diff = Date.now() - date.getTime();
      if (diff < 60000) return '刚刚';
      if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前';
      if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前';
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}-${day}`;
    },
    formatMessageTime(timestamp) {
      if (!timestamp) return '';
      const ts = Number(timestamp);
      if (isNaN(ts) || !isFinite(ts) || ts <= 0) return '';
      const date = new Date(ts.toString().length === 10 ? ts * 1000 : ts);
      if (isNaN(date.getTime())) return '';
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    trimMessage(message) {
      if (!message) return '';
      return message.length > 20 ? message.substring(0, 20) + '...' : message;
    },
    handleKeyDown(event) {
      if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
        event.preventDefault();
        this.sendTextMessage();
      }
    },
    getImageUrl(imageUrl) {
      if (!imageUrl) return '';
      if (imageUrl.startsWith('http')) return imageUrl;
      const baseUrl = 'https://api.sc123.shop/';
      if (imageUrl.startsWith('/')) {
        return baseUrl.replace(/\/+$/, '') + imageUrl;
      }
      return baseUrl + imageUrl;
    },
    previewImage(imageUrl) {
      window.open(imageUrl, '_blank');
    },
    // 确认删除聊天记录
    confirmDeleteChat(clientUuid) {
      if (!clientUuid) {
        this.$message.warning('请先选择一个用户');
        return;
      }
      this.$confirm('确定要删除该用户的所有聊天记录吗？此操作不可恢复。', '删除确认', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        danger: true
      }).then(() => {
        this.deleteChat(clientUuid);
      }).catch(() => {
        // 用户取消删除
      });
    },
    // 删除聊天记录
    async deleteChat(clientUuid) {
      if (!clientUuid) return;
      
      try {
        const response = await request({
          url: 'api/v1/chat/del',
          method: 'post',
          data: { client_uuid: clientUuid }
        });
        
        if (response.data.code === 200) {
          this.$message.success('删除成功');
          // 如果删除的是当前选中用户的消息，则返回列表
          if (this.selectedUser && this.selectedUser.client_uuid === clientUuid) {
            this.backToList();
          }
          // 刷新用户列表
          await this.fetchOnlineUsers();
        } else {
          this.$message.error(response.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除聊天记录失败:', error);
        this.$message.error('删除失败');
      }
    },
    startPolling() {
      this.stopPolling();
      this.pollTimer = setInterval(async () => {
        await this.fetchOnlineUsers();
        if (this.showDetail && this.selectedUser) {
          await this.loadMessages();
        }
      }, 4000);
    },
    stopPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer);
        this.pollTimer = null;
      }
    },
    refreshUsers() {
      this.fetchOnlineUsers();
      this.$message.success('已刷新');
    },
    disableZoom() {
      // 阻止触摸手势缩放
      document.addEventListener('touchstart', this.handleTouchStart, { passive: false });
      document.addEventListener('touchmove', this.handleTouchMove, { passive: false });
      document.addEventListener('touchend', this.handleTouchEnd, { passive: false });
      document.addEventListener('gesturestart', this.handleGestureStart);
      document.addEventListener('gesturechange', this.handleGestureChange);
      document.addEventListener('gestureend', this.handleGestureEnd);
    },
    enableZoom() {
      document.removeEventListener('touchstart', this.handleTouchStart);
      document.removeEventListener('touchmove', this.handleTouchMove);
      document.removeEventListener('touchend', this.handleTouchEnd);
      document.removeEventListener('gesturestart', this.handleGestureStart);
      document.removeEventListener('gesturechange', this.handleGestureChange);
      document.removeEventListener('gestureend', this.handleGestureEnd);
    },
    handleTouchStart(e) {
      if (e.touches.length > 1) {
        e.preventDefault();
      }
    },
    handleTouchMove(e) {
      if (e.touches.length > 1) {
        e.preventDefault();
      }
    },
    handleTouchEnd(e) {
      if (e.touches.length > 1) {
        e.preventDefault();
      }
    },
    handleGestureStart(e) {
      e.preventDefault();
    },
    handleGestureChange(e) {
      e.preventDefault();
    },
    handleGestureEnd(e) {
      e.preventDefault();
    }
  },
  async created() {
    await this.fetchOnlineUsers();
    this.startPolling();
  },
  mounted() {
    // 禁用移动端缩放
    this.disableZoom();
  },
  beforeDestroy() {
    this.stopPolling();
    // 移除缩放禁用
    this.enableZoom();
  }
};
</script>

<style scoped>
.chat-mobile-view {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px);
  background: #f5f7fa;
  touch-action: manipulation;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  user-select: none;
}

.mobile-header {
  padding: 12px 16px;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-refresh {
  font-size: 14px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-left: 8px;
}

.info-text {
  margin-left: 8px;
}

.user-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.user-status {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-dot.online {
  background: #67c23a;
}

.status-dot.offline {
  background: #c0c4cc;
}

.content-area {
  flex: 1;
  overflow: hidden;
}

.user-list {
  padding: 12px;
  overflow-y: auto;
  height: 100%;
}

.user-card {
  background: #ffffff;
  border-radius: 10px;
  padding: 14px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  margin-bottom: 12px;
  display: flex;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.user-card:active {
  transform: scale(0.98);
}

.card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.card-left {
  display: flex;
  flex: 1;
  margin-right: 10px;
}

/* 删除按钮样式 - 蓝色文本 */
.delete-button {
  color: #1890ff;
  font-size: 13px;
  padding: 4px 8px;
}

.delete-button:hover,
.delete-button:focus {
  color: #40a9ff;
  background: transparent;
  border-color: transparent;
}

.avatar-wrapper {
  position: relative;
  margin-right: 12px;
}

.unread-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  min-width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  background: #f56c6c;
  color: #fff;
  font-size: 12px;
  border-radius: 10px;
  padding: 0 4px;
}

.card-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.card-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.card-status {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 6px;
}

.card-message {
  font-size: 13px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.last-time {
  font-size: 11px;
  color: #c0c4cc;
}

.empty-state {
  margin-top: 40px;
}

.chat-detail {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  background: #f4f6f8;
}

.message-row {
  display: flex;
  margin-bottom: 12px;
}

.message-row.customer {
  justify-content: flex-start;
}

.message-row.service {
  justify-content: flex-end;
}

.message-bubble {
  max-width: 85%;
  border-radius: 12px;
  padding: 10px 12px;
  background: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  position: relative;
  word-break: break-word;
}

.message-row.service .message-bubble {
  background: #1890ff;
  color: #ffffff;
}

.message-text {
  font-size: 15px;
  line-height: 1.5;
}

.message-image-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 6px;
}

.message-row.service .message-image-wrapper {
  align-items: flex-end;
}

.message-image {
  max-width: 220px;
  border-radius: 10px;
  object-fit: cover;
  cursor: pointer;
}

.message-caption {
  font-size: 13px;
  line-height: 1.4;
}

.caption-title {
  font-weight: 600;
}

.caption-price {
  color: #ff5722;
  font-weight: 700;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  margin-top: 6px;
  text-align: right;
}

.empty-messages {
  padding: 40px 0;
  text-align: center;
  color: #909399;
}

.input-area {
  padding: 12px;
  background: #ffffff;
  border-top: 1px solid #ebeef5;
}

.input-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 8px;
  gap: 10px;
}

.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.2s ease;
}

.fade-slide-enter,
.fade-slide-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

@media (min-width: 769px) {
  .chat-mobile-view {
    max-width: 480px;
    margin: 0 auto;
    border: 1px solid #ebeef5;
    border-radius: 12px;
    overflow: hidden;
  }
}
</style>

